<script setup lang="ts" generic="T">
import type { ComponentExposed } from 'vue-component-type-helpers'

import type DataForm from '../DataForm/DataForm.vue'
import type { DataFormField } from '../DataForm/types'
import type { PageRes } from '@/apis/common/commonApi'
import { ref } from 'vue'

const { fields } = defineProps<{
  fields: DataFormField<T>[]
  cols?: 1 | 2 | 3 | 4
}>()

const emits = defineEmits(['submit'])
const formData = defineModel<PageRes | any>('formData', { required: true })

const formRef = ref<ComponentExposed<typeof DataForm>>()

function doSearch() {
  formData.value.current = 1
  formRef.value?.submitForm()
}

defineExpose({ submitForm: () => formRef.value?.submitForm() })
</script>

<template>
  <data-form
    ref="formRef"
    v-model="formData"
    :fields="fields"
    :cols="cols ?? 4"
    :submit="async (data) => await emits('submit', data)"
  >
    <template v-for="field in fields" #[field.name]>
      <slot :name="field.name" :data="formData" />
    </template>
    <template v-if="formRef" #append>
      <el-button @click="formRef.resetForm">
        重置
      </el-button>
      <el-button type="primary" :loading="formRef.formLoading" @click="doSearch">
        搜索
      </el-button>
    </template>
  </data-form>
</template>
